<?php
// +----------------------------------------------------------------------
// | 陵园管理
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\CemeteryModel;
use app\admin\model\TombareaModel;
use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\AdminMenuModel;
use think\Model;
use tree\Tree;
use think\facade\Request;

class CemeteryController extends AdminBaseController
{

    protected $cemetery_model;
    public function initialize()
    {
		$this->cemetery_model = new CemeteryModel();
        parent::initialize();
    } 
	public function index(){
        //查询墓区信息
        $result = $this->cemetery_model->cacheCemeteryData();
        $tree = new Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $newmenus=array();
        foreach ($result as $m){
        	$newmenus[$m['id']]=$m;
        }
        foreach ($result as $n=> $r) {
        	
        	$result[$n]['level'] = $this->_get_level($r['id'], $newmenus);
        	$result[$n]['parent_id_node'] = ($r['parent_id']) ? ' class="child-of-node-' . $r['parent_id'] . '"' : '';
        	if($result[$n]['type'] != "层"){
				$result[$n]['str_manage'] ='<a href="' . url("Cemetery/add", array("parentid" => $r['id'], "id" => input("get.id"))) . '">'.lang('ADD_SUB_MENU').'</a> | ';
			}
			$result[$n]['str_manage'] = isset($result[$n]['str_manage'])?$result[$n]['str_manage']:'';
//            $result[$n]['str_manage'] .= '<a href="' . url("Cemetery/edit", array("parentid" => $r['parent_id'],"id" => $r['id'], "menuid" => input("get.id"))) . '">'.lang('EDIT');
            $result[$n]['str_manage'] .= '<a href="' . url("Cemetery/edit", array("parentid" => $r['parent_id'],"id" => $r['id'], "menuid" => input("get.id"))) . '">'.lang('EDIT').'</a> | <a class="js-ajax-delete" href="' . url("Cemetery/delete", array("id" => $r['id'], "menuid" => input("get.id")) ). '">'.lang('DELETE').'</a> ';
            if($result[$n]['type'] == "层"||$result[$n]['type'] == "园") {
                $result[$n]['str_manage'] .= ' | <a href="' . url("tombarea/index", array("parentid" => $r['parent_id'],"id" => $r['id'], "menuid" => input("get.id"))) . '">墓区管理</a> ';
                $result[$n]['str_manage'] .= ' | <a href="' . url("tombarea/add", array("parentid" => $r['parent_id'],"id" => $r['id'], "menuid" => input("get.id"))) . '">创建墓区</a> ';
            }
			$result[$n]['is_generate'] = $r['is_generate']==1 ? '是' : '否';
            $result[$n]['status'] = $r['status']==1 ? lang('DISPLAY') : lang('HIDDEN');
            if(APP_DEBUG){
				$r['app'] = isset($r['app'])?$r['app']:'';
				$r['model'] = isset($r['model'])?$r['model']:'';
				$r['action'] = isset($r['action'])?$r['action']:'';
            	$result[$n]['app']=$r['app']."/".$r['model']."/".$r['action'];
            }
        }


        $tree->init($result);
        $str = "<tr id='node-\$id' \$parent_id_node>
					<td style='padding-left:20px;'><input name='list_orders[\$id]' type='text' class='form-control' size='3' value='\$list_order' class='input input-order'></td>
        			<td>\$name</td>
<!--					<td>\$is_generate</td>-->
				    <td>\$status</td>
					<td>\$str_manage</td>
				</tr>";
        $categorys = $tree->getTree(0, $str);
        $this->assign("categorys", $categorys);
		return $this->fetch();
	}
	public function add(){
        if ($this->request->isPost()){
            $data = $this->request->param();
            if($data['parentid']==0){
                $data['type']  = '陵园';
            }else{
                $type = $this->cemetery_model->where(array('id'=>$data['parentid']))->find();
                if($type['type']=='陵园'){
                    $data['type']  = '区';
                }elseif ($type['type']=='区'){
                    $data['type']  = '园';
                }
                elseif ($type['type']=='园'){
                    $data['type']  = '层';
                }
            }
            $data['parent_id'] = $data['parentid'];
            $data['list_order'] = 0;
            $data['is_generate'] = 2;//是否生成墓区
            unset($data['parentid']);
            $this->cemetery_model->insertGetId($data);
            $this->cemetery_model->cacheCemeteryData(1);
           return $this->success("添加成功", url('index'));
        }
		$tree = new Tree();
		$parentid = $this->request->param('parentid', 0, 'intval');

        $result = $this->cemetery_model->cacheCemeteryData();

//    	$result = $this->cemetery_model->order(array("list_order" => "ASC"))->where("is_delete",0)->where('type','neq',"层")->select()->toArray();
        $array = [];
    	foreach ($result as $r) {
    		$r['selected'] = $r['id'] == $parentid ? 'selected' : '';
    		$array[] = $r;
    	}
    	$str = "<option value='\$id' \$selected>\$spacer \$name</option>";
    	$tree->init($array);
    	$select_categorys = $tree->getTree(0, $str);
    	$this->assign("parentid",$parentid);
    	$this->assign("select_categorys", $select_categorys);
		return $this->fetch();
	}

	public function add_post()
    {
        $data = $this->request->param();
        if($data['parentid']==0){
            $data['type']  = '陵园';
        }else{
            $type = $this->cemetery_model->where(array('id'=>$data['parentid']))->find();
            if($type['type']=='陵园'){
                $data['type']  = '区';
            }elseif ($type['type']=='区'){
                $data['type']  = '园';
            }
            elseif ($type['type']=='园'){
                $data['type']  = '层';
            }
        }
        $data['parent_id'] = $data['parentid'];
        $data['list_order'] = 0;
        $data['is_generate'] = 2;//是否生成墓区
        unset($data['parentid']);
        $this->cemetery_model->insertGetId($data);
        $this->cemetery_model->cacheCemeteryData(1);
        $this->success("添加成功", url('cemetery/index'));
    }
    /*
     * 编辑
     */
    public function edit()
    {
        $id = $this->request->param("id",0,'intval');

        $result_info = Db::name("cemetery")->where(['id'=>$id])->find();
        $tree = new Tree();
        $parentid = $this->request->param('parent_id', 0, 'intval');

        $result_list = Db::name("cemetery")->where("is_delete",0)->order("list_order ASC")->select()->toArray();

        foreach ($result_list as $r) {
            $r['selected'] = $r['id'] == $result_info['parent_id'] ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $select_categorys = $tree->getTree(0, $str);
        $this->assign("parentid",$parentid);
        $this->assign("select_categorys", $select_categorys);
        $this->assign($result_info);
        return $this->fetch();
    }
    public function edit_post()
    {
        if ($this->request->isPost()) {
            $arrData  = $this->request->post();
            $arrData['parent_id'] = $arrData['parentid'];
			
			$id = $arrData['id'];
			unset($arrData['id']);
            unset($arrData['parentid']);

            if($arrData['parent_id']==0){
                $arrData['type']  = '陵园';
            }else{
                $type = Db::name("cemetery")->where('id',$arrData['parent_id'])->find();

                if($type['type']=='陵园'){
                    $arrData['type']  = '区';
                }elseif ($type['type']=='区'){
                    $arrData['type']  = '园';
                }elseif ($type['type']=='园'){
                    $arrData['type']  = '层';
                }
            }
            $this->cemetery_model->where(['id'=>$id])->update($arrData);
            $this->cemetery_model->cacheCemeteryData(1);
            $this->success('编辑成功', url('index'));
        }
    }

    public function listOrder()
    {
        parent::listOrders($this->cemetery_model);
        $this->success("排序成功！");
    }
    /**
     * 物理删除数据
     **/
    public function delete(){
        // 需要删除的数据ID
        $id = $this->request->param("id",0,'intval');
        // 判断是否为物理删除
        //dump($this->config);exit;
        if($this->config['REAL_DELETE']){
            if ($this->cemetery_model->where(array('id'=>$id))->delete()!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        } else {
            $info = $this->cemetery_model->where(['parent_id'=>$id,'is_delete'=>0])->find();
            if (!$info){
               $infi_tomb =  TombareaModel::where(['cemetery_id'=>$id])->find();
               if (!$infi_tomb){
                   $saveData = array( 'is_delete'	=> 1);
                  if ($this->cemetery_model->where(['id'=> $id])->update($saveData)!==false) {
                      $this->cemetery_model->cacheCemeteryData(1);
                      $this->success("删除成功！");
                  } else {
                      $this->error("删除失败！");
                  }
               }else{
                   $this->error( '含有子类，删除失败');
               }
            }else{
                $this->error( '含有子类，删除失败');
            }
        }
    }
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
        if ($array[$id]['parent_id']==0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id']==$id){
            return  $i;
        }else{
            $i++;
            return $this->_get_level($array[$id]['parent_id'],$array,$i);
        }
        		
    }
}